package com.gimi.cloud.bbp.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.client.service.sys.SysResourceService;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.DateUtil;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.RandomUtil;
import com.gimi.cloud.bbp.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.common.utils.reqhead.Util;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.dto.sys.SysResourceDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统通用功能
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2018-01-26
 **/
@Controller
@RequestMapping("/public")
public class PublicController {
    private static final Logger logger = LoggerFactory.getLogger(PublicController.class);

    private RedisService redisService;
    private SysResourceService sysResourceService;

    @Autowired
    public PublicController(RedisService redisService, SysResourceService sysResourceService) {
        this.redisService = redisService;
        this.sysResourceService = sysResourceService;
    }

    /**
     * 文件上传接口
     * @param multipartFile
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/fileupload")
    public void fileUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file")MultipartFile multipartFile, @RequestParam("type")String type) throws Exception{
        Response resp = new Response();
        InputStream is = multipartFile.getInputStream();
        //获取当前配置的上传路径地址
        JSONObject dirPathConfig =redisService.getJSONObjectConfigByKey(RedisKeyConstant.CONFIG_KEY_PUBLIC_ALIOSS_PATH);
        //判断是否配置有该类型的路径，如果没有，直接返回文件类型错误
        if (null == dirPathConfig || !dirPathConfig.containsKey(type)) {
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"未获取到配置的文件");
        }
        //获取到当前类型的配置信息
        dirPathConfig = dirPathConfig.getJSONObject(type);
        //获取文件类型
        String[] originalFilenames = multipartFile.getOriginalFilename().split("\\.");
        //新的文件名称
        String fileName =  DateUtil.dateStr3(new Date()) + "" + RandomUtil.getRandomRange(999, 100) +"." + originalFilenames[originalFilenames.length-1];
        //上传文件
        String result = AliOSSUtil.uploadFile(is,dirPathConfig.getString("path"),fileName);
        Map<String,String> data = new HashMap<>(10);
        //获取当前类型配置的有效时间
        String url = AliOSSUtil.getFileUrl(result,dirPathConfig.getLong("second"));
        data.put("url",url);
        data.put("shortUrl",result);
        data.put("extra",request.getParameter("extra"));
        SysResourceDTO sysResourceDTO = new SysResourceDTO();
        sysResourceDTO.setReFileType(originalFilenames[originalFilenames.length-1]);
        sysResourceDTO.setReType(type);
        sysResourceDTO.setReName(multipartFile.getOriginalFilename());
        sysResourceDTO.setReOssUrl(result);
        sysResourceDTO.setReUrl(url);
        sysResourceDTO.setReTypeName(dirPathConfig.getString("typeName"));
        sysResourceService.saveOrUpdate(sysResourceDTO);
        resp.setRes_data(data);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }
    /**
     * 根据文件名称获取AliOss路径
     * @param request
     * @param response
     * @param fileName 文件名称
     * @throws Exception
     */
    @RequestMapping("/getFilePath")
    public void getFilePath(HttpServletRequest request,HttpServletResponse response,@RequestParam("fileName")String fileName) throws Exception{
        //涉及缓存，默认超时时间为一年
        String url = AliOSSUtil.getFileUrl(fileName,60 * 60 * 24 * 365);
        Response resp = new Response();
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        resp.setRes_data(url);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }
}
